﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text;

namespace CivilleWebRole
{
    public partial class EditTask : System.Web.UI.Page
    {
        public const string TASK_LOGO_PATH = "htt" + "p://civillehostedservices.cloudapp.net/Logo/Tasks/";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/NotAuthorized.aspx");
            }

            // check business type = > task type (table in db)
            SliderExtender.Maximum = 300;
            SliderExtender.Steps = (int)(SliderExtender.Maximum / 5 + 1);
        }

        protected void SaveTaskButtonClick(object sender, EventArgs e)
        {
            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = connection.CreateCommand();
            SqlCommand getStakeholderIDCommand = connection.CreateCommand();
            getStakeholderIDCommand.CommandText = "SELECT ID FROM Stakeholder WHERE Name = '" + User.Identity.Name + "'";
            connection.Open();
            int stakeholderID = (int)getStakeholderIDCommand.ExecuteScalar();

            if (this.FileUpload.HasFile)
            {
                if (isLogoSaved())
                {   //todo replace TaskType
                    String id = (Convert.ToInt32(getLastId()) + 1).ToString();
                    //         String path = Server.MapPath("Logo/Tasks/" + id + System.IO.Path.GetExtension(FileUpload.FileName).ToLower());
                    String fileExtension = System.IO.Path.GetExtension(FileUpload.FileName).ToLower();
                    command.CommandText = "INSERT INTO [Task] ([Title], [Description], [TaskTypeID], [Latitude], [Longitude], [Points], [Logo], [StakeholderID]) VALUES ('"
                       + TitleTxt.Text + "', '" + DescriptionTxt.Text + "', '" + 2 + "', '" + LatitudeTxt.Text + "', '" + LongitudeTxt.Text + "', '" + PointsTxt_BoundControl.Text + "', '" + TASK_LOGO_PATH + id + fileExtension + "', '" + stakeholderID + "')";
                }
            }
            else
            {
                //   String path = Server.MapPath("Logo/Tasks/default.jpg");
                String path = "default.jpg";
                command.CommandText = "INSERT INTO [Task] ([Title], [Description], [TaskTypeID], [Latitude], [Longitude], [Points], [Logo], [StakeholderID]) VALUES ('"
                   + TitleTxt.Text + "', '" + DescriptionTxt.Text + "', '" + 2 + "', '" + LatitudeTxt.Text + "', '" + LongitudeTxt.Text + "', '" + PointsTxt_BoundControl.Text + "', '" + TASK_LOGO_PATH + path + "', '" + stakeholderID + "')";
            }

            command.ExecuteNonQuery();

            // generate 20 QRCodes
            QRCodeGenerator generator = new QRCodeGenerator();
            for (int i = 0; i < 20; i++)
            {
                String code = generator.generateRandomString();
                SqlCommand createQRCodescommand = connection.CreateCommand();
                createQRCodescommand.CommandText = "INSERT INTO [QRCode] ([Code], [Status], [TaskID]) VALUES ('" + code + "', 'true', '" + getLastId() + "')";
                createQRCodescommand.ExecuteNonQuery();
            }

            connection.Close();

            // Send Tile Notification
            SendTile();
        }

        private List<String> GetMobileUsers()
        {
            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT URI FROM MobileUsers";
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            List<String> URIs = new List<String>();
            while (reader.Read())
            {
                URIs.Add(reader[0].ToString());
            }
            reader.Close();
            connection.Close();
            return URIs;
        }

        private void SendTile()
        {
            List<String> URIs = GetMobileUsers();

            foreach (String URI in URIs)
            {
                String tileResponse;
                try
                {
                    // Get the URI that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
                    // Normally, a web service would listen for URIs coming from the web client and maintain a list of URIs to send
                    // notifications out to.
                    string subscriptionUri = URI;


                    HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);

                    // Create an HTTPWebRequest that posts the Tile notification to the Microsoft Push Notification Service.
                    // HTTP POST is the only method allowed to send the notification.
                    sendNotificationRequest.Method = "POST";

                    // The optional custom header X-MessageID uniquely identifies a notification message. 
                    // If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
                    // sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");

                    // Create the Tile message.
                    string tileMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<wp:Notification xmlns:wp=\"WPNotification\">" +
                        "<wp:Tile>" +
                          "<wp:BackgroundImage>" + "/Resources/TileBackgrounds/CivilleBackground.png" + "</wp:BackgroundImage>" +
                          "<wp:Count>" + 1 + "</wp:Count>" +
                          "<wp:Title>" + "Hey there!" + "</wp:Title>" +
                          "<wp:BackBackgroundImage>" + "/Resources/TileBackgrounds/CivilleBackBackground.png" + "</wp:BackBackgroundImage>" +
                          "<wp:BackTitle>" + "Civille" + "</wp:BackTitle>" +
                          "<wp:BackContent>" + "There are new tasks!" + "</wp:BackContent>" +
                       "</wp:Tile> " +
                    "</wp:Notification>";

                    // Set the notification payload to send.
                    byte[] notificationMessage = Encoding.Default.GetBytes(tileMessage);

                    // Set the web request content length.
                    sendNotificationRequest.ContentLength = notificationMessage.Length;
                    sendNotificationRequest.ContentType = "text/xml";
                    sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "token");
                    sendNotificationRequest.Headers.Add("X-NotificationClass", "1");


                    using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                    {
                        requestStream.Write(notificationMessage, 0, notificationMessage.Length);
                    }

                    // Send the notification and get the response.
                    HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                    string notificationStatus = response.Headers["X-NotificationStatus"];
                    string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                    string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

                    // Display the response from the Microsoft Push Notification Service.  
                    // Normally, error handling code would be here. In the real world, because data connections are not always available,
                    // notifications may need to be throttled back if the device cannot be reached.
                    tileResponse = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
                }
                catch (Exception ex)
                {
                    tileResponse = "Exception caught sending update: " + ex.ToString();
                }
            }
        }

        protected bool isLogoSaved()
        {
            String path = "";
            if (this.FileUpload.HasFile)
            {
                if (CheckFileType(FileUpload.FileName))
                {
                    String id = (Convert.ToInt32(getLastId()) + 1).ToString();
                    path = Server.MapPath("/Logo/Tasks/" + id + System.IO.Path.GetExtension(FileUpload.FileName).ToLower());
                }
                else
                {
                    StatusLabel.Text = "The selected image is not valid!";
                    return false;
                }
            }

            try
            {
                this.FileUpload.SaveAs(path);
            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Could not save the logo!";
                return false;
            }

            return true;
        }

        protected String getLastId()
        {
            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT IDENT_CURRENT('Task')";
            connection.Open();
            String rsIdentity = command.ExecuteScalar().ToString();
            connection.Close();
            return rsIdentity;
        }

        protected bool checkUploadedFile(FileUpload fu)
        {
            if (CheckFileType(fu.FileName))
            {
                if (fu.PostedFile.ContentLength < 2097151)
                {
                    return true;
                }
            }
            return false;
        }

        bool CheckFileType(string fileName)
        {
            string ext = Path.GetExtension(fileName);
            switch (ext.ToLower())
            {
                case ".gif":
                    return true;
                case ".png":
                    return true;
                case ".jpg":
                    return true;
                case ".jpeg":
                    return true;
                default:
                    return false;
            }
        }
    }
}
